package com.mingxun.project.http;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.mingxun.project.MyApplication;
import com.mingxun.project.http.exception.ExceptionEngine;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Type;

import io.reactivex.Observable;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.Okio;
import retrofit2.Converter;

/**
 * class name：
 *
 * @author liuhongyuan.
 * @date 2017/12/19
 */

public class FastJsonResponseConverter<T> implements Converter<ResponseBody, T> {
    private final Type type;

    public FastJsonResponseConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        BufferedSource bufferedSource = Okio.buffer(value.source());
        String tempStr = bufferedSource.readUtf8();
        Log.i("hy", "convert: "+tempStr);
        bufferedSource.close();
        try {
            if (MyApplication.getInstance().isShouldReplace()) {
                MyApplication.getInstance().setShouldReplace(false);
                tempStr = tempStr.replace(":[]", ":{}");
                return JSON.parseObject(tempStr.replace(":[]", ":{}"), type);
            } else {
                return JSON.parseObject(tempStr, type);
            }
        } catch (Exception e) {
            try {
                Object obj = JSON.parseObject(tempStr, ((Class) type).getSuperclass());
                Class typeClass = ((Class) type);
                Observable.error(ExceptionEngine.handleException(e));
                Constructor<T> tConstructor= typeClass.getConstructor(typeClass.getSuperclass());
                return tConstructor.newInstance(obj);
            } catch (Exception e2) {
                throw new IOException("数据异常，数据解析失败！");
            }
        }
    }
}
